<template>
  <el-dialog :title="!dataForm.id ?  '不合格品详情': '不合格品详情'" :close-on-click-modal="false" :visible.sync="visible"
    fullscreen center>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" inline ref="dataForm" label-width="90px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="申报部门" prop="deptId">
            <el-input v-model="dataForm.deptName"></el-input>
            <!--<el-select v-model="dataForm.deptId" placeholder="请选择" @change="deptNameChange($event)">
                <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申报仓库">
            <el-input v-model="dataForm.stockName"></el-input>
            <!--<el-select v-model="dataForm.stockId" placeholder="请选择"  @change="stockNameChange($event)">
                <el-option v-for="item in stockOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="责任人" prop="dutyUser">
            <el-select v-model="dataForm.dutyUser" placeholder="请选择">
              <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" show-summary :summary-method="getSummaries"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column prop="goodsBarcode" label="商品编号"></el-table-column>
      <el-table-column prop="goodsName" label="商品名称"></el-table-column>
      <el-table-column prop="reason1" label="不合格品原因">
        <template slot-scope="scope">
          <el-select v-model="scope.row.reason1" placeholder="请选择原因" @change="getSecondReasonList">
            <el-option v-for="item in reasonOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="reason2" label="不合格品现象">
        <template slot-scope="scope">
          <el-select v-model="scope.row.reason2" placeholder="请选择现象">
            <el-option v-for="item in reasonSecondOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="goodsQuantity" label="数量">
        <template slot-scope="scope">
          <el-input v-model="scope.row.goodsQuantity"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="handleMenthod" label="处理">
        <template slot-scope="scope">
          <el-select v-model="scope.row.handleMenthod" placeholder="请选择现象">
            <el-option label="报残" value="1"></el-option>
            <el-option label="退回" value="2"></el-option>
          </el-select>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" type="primary">关闭</el-button>
    </span>
    <bill-list v-if="singleListVisible" ref="billOrSingle" @showBrandList="getBrandData"></bill-list>
    <order-detail v-if="detailVisible" ref="detailDialog"></order-detail>
  </el-dialog>
</template>

<script>
  import {
    editUnqualifiedObj,
    getUnqualifiedById,
    addUnqualifiedObj
  } from '@/api/eims/unqualified'
  import { getStockList } from '@/api/eims/stock'
  import { fetchTree } from '@/api/admin/dept'
  import { getUserListNoRole } from '@/api/admin/user'
  import { getUnqualifiedReasonList } from '@/api/eims/unqualifiedreason'

  import BillList from './billlist'
  import AvueIframe from "../../../components/iframe/main" //商品信息查询组件
  // import OrderDetail from './detail'

  export default {
    data() {
      return {
        visible: false,
        singleListVisible: false,
        detailVisible: false,
        dataListLoading: false,
        dataForm: {
          status: '0', // 是否审核 0-未审核,1-已审核,2-已处理
          autoStatus: '0', // 是否生成调拨单(1-是,0-否)
          billId: '', // 调拨单号
          deptId: '', // 申报部门
          deptName: '', // 申报部门名称
          stockId: '', // 申报仓库
          stockName: '', // 申报仓库
          createUser: '', //  制单人
          dutyUser: '', //  责任人
          detailList: []
        },
        // verify: false,
        dataList: [],
        deptOptions: [],
        userOptions: [],
        stockOptions: [],
        selectionList: [],
        reasonOption: [],
        reasonSecondOption: [],
        dataRule: {
          deptId: [{
            required: true,
            message: '申报部门不能为空'
          }],
          stockId: [{
            required: true,
            message: '申报仓库不能为空'
          }]
        }
      }
    },
    components: {
      AvueIframe,
      BillList
      //OrderDetail
    },
    methods: {
      init(id) {
        this.getDeptList()
        this.getUserList()
        this.getParentReasonList()
        this.dataForm.detailList = []
        this.dataList = []
        this.dataForm.stockId = ''
        this.stockOptions = []
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.dataListLoading = true
            getUnqualifiedById(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data
                this.dataList = response.data.data.detailList
                this.dataList.forEach(item => {
                  this.getSecondReasonList(item.reason1)
                })
              }else{
                this.$message.error(response.data.msg)
              }
              this.dataListLoading = false
            })
          }
        })
      },
      deptNameChange($event) {
        this.deptOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.deptName = item.label
          }
        })
        this.getOutStockList($event);
      },
      stockNameChange($event) {
        this.stockOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.stockName = item.label
          }
        })
      },
      // 获取员工用户列表
      getUserList(id) {
        getUserListNoRole({unitId: id}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let userList = []
            resultData.forEach(item => {
              let userObj = {
                value: item.id,
                label: item.realName
              }
              userList.push(userObj)
            })
            this.userOptions = userList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取部门列表
      getDeptList() {
        fetchTree().then(response => {
          if(response.data.code == '0'){
            let deptList = []
            let resultData = response.data.data
            resultData.forEach(item => {
              let deptObj = {
                value: item.id,
                label: item.name
              }
              deptList.push(deptObj)
            })
            this.deptOptions = deptList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取库仓位列表
      getOutStockList(id) {
        this.dataForm.stockId = ''
        this.stockOptions = [];
        getStockList({deptId: id}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let stockList = []
            resultData.forEach(item => {
              let stockObj = {
                value: item.id,
                label: item.name
              }
              stockList.push(stockObj)
            })
            this.stockOptions = stockList
            this.dataForm.stockId = resultData[0].id
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取不合格品现象原因列表
      getParentReasonList() {
        this.reasonOption = [];
        getUnqualifiedReasonList({parentId: 0}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let reasonList = []
            resultData.forEach(item => {
              let reasonObj = {
                value: item.id,
                label: item.name
              }
              reasonList.push(reasonObj)
            })
            this.reasonOption = reasonList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      getSecondReasonList(id) {
        this.reasonSecondOption = [];
        this.dataForm.detailList.reason2 = '';
        getUnqualifiedReasonList({parentId: id}).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let reasonList = []
            resultData.forEach(item => {
              let reasonObj = {
                value: item.id,
                label: item.name
              }
              reasonList.push(reasonObj)
            })
            this.reasonSecondOption = reasonList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //添加详情里的数据
            this.dataForm.detailList.forEach((item, index) => {
              item.goodsQuantity = this.dataList[index].goodsQuantity,
                item.handleMenthod = this.dataList[index].handleMenthod,
                item.reason1 = this.dataList[index].reason1,
                item.reason2 = this.dataList[index].reason2,
                item.goodsName = this.dataList[index].goodsName
            })
            if (this.dataForm.id) {
              editUnqualifiedObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success("修改成功")
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              })
            } else {
              addUnqualifiedObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success(data.data)
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
              })
            }
          }
        })
      },
      // 按单品添加商品
      openTableList(name) {
        let data = {
          data: this.dataList,
          params: {
            stockId: this.dataForm.stockId
          }
        }
        if (name == 'single') {
          this.singleListVisible = true
          this.$nextTick(() => {
            this.$refs.billOrSingle.init(data)
          })
        } else if (name == 'detail') {
          this.detailVisible = true
          this.$nextTick(() => {
            this.$refs.detailDialog.init(data)
          })
        }
      },
      // 多选表格表格变化事件
      handleSelectionChange(val) {
        this.selectionList = val
      },
      // 删除商品详情列表中的商品
      delTableData() {
        let data = this.selectionList
        data.forEach(item => {
          this.dataList.splice(item, 1)
        })
      },
      // bill-list  自定义事件
      getBrandData(obj) {
        let _this = this
        this.dataList = obj
        obj.forEach(item => {
          this.dataForm.detailList.push({
            goodsId: item.goodsId,
            goodsQuantity: item.goodsQuantity
          })
        })
      },
      //  合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 4) {
            sums[index] = '合计';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if (index == 5) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        return sums;
      }
    }
  }
</script>
<style lang="scss" scoped>
  /deep/ .el-table {
    display: flex;
    flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
    order: 1;
  }
</style>
